package com.photoeditor.demo.ui.widget.image;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;

import com.common.base.ComponentContext;
import com.photoeditor.R;
import com.photoeditor.demo.db.FilterBean;
import com.photoeditor.demo.db.FilterConstant;
import com.photoeditor.demo.model.filter.ImageFilterTools;
import com.photoeditor.demo.model.preference.SPDataManager;
import com.photoeditor.demo.ui.activity.edit.MediaEditBaseActivity;
import com.photoeditor.demo.ui.widget.AnimationTextView;

import java.util.List;

/**
 * 滤镜的Adapter
 */
public class FilterAdapter extends ArrayAdapter<FilterBean> {

    private int SeletcItemPosition = 1;

    private ImageView mImageView;

    private final int mImageViewId = 1001;

    private boolean mShowNew;

    private Context mContext;

    /**
     * 需要显示的数据
     */
    private List<FilterBean> mData;

    private LayoutInflater mInfl;

    public static final int MAIN_FILTER_TYPE = 1;

    public static final int Edit_FILTER_TYPE = 2;

    public static final int VIDEO_FILTER_TYPE = 3;

    public static final int COLLAGE_FILTER_TYPE = 4;

    private int mType;

    private final int mTextHeight;
    private final int mTextMaxHeight;

    private FilterIconManager mIconManager;

    private final int mOriginalBgColor;

    public FilterAdapter(Context context, List<FilterBean> data, int type) {
        super(context, 0, data);
        this.mContext = context;
        this.mData = data;
        this.mInfl = ((Activity) context).getLayoutInflater();
        mType = type;

        Resources res = context.getResources();

        mTextHeight = res.getDimensionPixelSize(R.dimen.filter_text_height);
        mTextMaxHeight = res.getDimensionPixelSize(R.dimen.filter_height);
        mOriginalBgColor = res.getColor(R.color.original_tv_bg);

        if (type == MAIN_FILTER_TYPE) {
            mImageView = new ImageView(context);
            mImageView.setLayoutParams(new RelativeLayout.LayoutParams(mTextMaxHeight, mTextMaxHeight));
//			mImageView.setImageResource(R.drawable.main_filter_take_photo_selector);
            mImageView.setScaleType(ScaleType.CENTER);
            mImageView.setId(mImageViewId);
        } else if (type == Edit_FILTER_TYPE || type == VIDEO_FILTER_TYPE) {
            mIconManager = new FilterIconManager((MediaEditBaseActivity) context);
        }
        mShowNew = SPDataManager.getHasNewFilter();
        SeletcItemPosition = 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInfl.inflate(R.layout.item_filter, null);
            holder.icon = (ImageView) convertView.findViewById(R.id.filter_item_image);
            holder.label = (AnimationTextView) convertView.findViewById(R.id.filter_item_text);
            holder.vipIcon = (ImageView) convertView.findViewById(R.id.img_vip);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        final FilterBean data = mData.get(position);
        int type = data.getType();

        if (data.isBuy()) {
            holder.vipIcon.setVisibility(View.VISIBLE);
        } else {
            holder.vipIcon.setVisibility(View.INVISIBLE);
        }
        if (mType == MAIN_FILTER_TYPE || mType == VIDEO_FILTER_TYPE || mType == COLLAGE_FILTER_TYPE) {
            //先恢复默认
            holder.icon.setImageBitmap(null);

			/*if (type == FilterConstant.TYPE_BUILDIN) {
				holder.icon.setImageResource(ImageFilterTools.BUILDIN_FILTER_ICON_RESID.get(data.getPackageName()));
				holder.label.setBgColor(data.getColor());
				holder.label.setText(data.getName());
				holder.label.setVisibility(View.VISIBLE);
			} else */
            if (type == FilterConstant.TYPE_DOWNLOAD) {
                ImageFilterTools.setImage(holder.icon, ComponentContext.getContext(),
                        data.getPackageName(), data.getApkUri(), data.getImageUrl());
                holder.label.setBgColor(data.getColor());
                holder.label.setText(data.getName());
                holder.label.setVisibility(View.VISIBLE);
            } else if (type == FilterConstant.TYPE_MORE) {
//				if(mShowNew) {
//					holder.icon.setImageResource(R.drawable.image_edit_filter_store_new_selector_blue);
//				} else {
//					holder.icon.setImageResource(R.drawable.image_edit_filter_store_selector_blue);
//				}
                holder.label.setVisibility(View.GONE);
            } else if (type == FilterConstant.TYPE_ORIGINAL) {
                holder.icon.setImageResource(R.drawable.ic_original);
                holder.label.setBgColor(mOriginalBgColor);
                holder.label.setText(data.getName());
                holder.label.setVisibility(View.VISIBLE);
            }
        } else {
            //先恢复默认
            holder.icon.setImageBitmap(null);

            if (type == FilterConstant.TYPE_MORE) {
                holder.icon.setTag(null);
//				if(mShowNew) {
//					holder.icon.setImageResource(R.drawable.image_edit_filter_store_new_selector_blue);
//				} else {
//					holder.icon.setImageResource(R.drawable.image_edit_filter_store_selector_blue);
//				}
                holder.label.setVisibility(View.GONE);
            } else if (type == FilterConstant.TYPE_ORIGINAL) {
                holder.icon.setTag(data);
                mIconManager.loadIcon(holder.icon, data);
                holder.label.setBgColor(mOriginalBgColor);
                holder.label.setText(data.getName());
                holder.label.setVisibility(View.VISIBLE);
            } else {
                holder.icon.setTag(data);
                mIconManager.loadIcon(holder.icon, data);
                holder.label.setBgColor(data.getColor());
                holder.label.setText(data.getName());
                holder.label.setVisibility(View.VISIBLE);
            }
        }
        if (convertView != null) {
            if (type == FilterConstant.TYPE_MORE) {//more
                holder.label.setProgressAndCancelAnimation(0, true);
                if (mType == MAIN_FILTER_TYPE) {
                    RelativeLayout layout = (RelativeLayout) convertView;
                    View iview = layout.findViewById(mImageViewId);
                    if (iview != null) {
                        layout.removeView(mImageView);
                    }
                }
            } else {
                if (mType == MAIN_FILTER_TYPE) {
                    if (position == SeletcItemPosition) {
                        holder.label.setProgressAndCancelAnimation(100, false);
                    } else {
                        holder.label.setProgressAndCancelAnimation(0, true);
                    }
                    RelativeLayout layout = (RelativeLayout) convertView;
                    View iview = layout.findViewById(mImageViewId);
                    if (position == SeletcItemPosition) {
                        if (iview == null) {
                            ViewParent viewP = mImageView.getParent();
                            if (viewP != null) {
                                RelativeLayout playout = (RelativeLayout) viewP;
                                playout.removeView(mImageView);
                            }
                            layout.addView(mImageView);
                        }
                    } else {
                        if (iview != null) {
                            layout.removeView(mImageView);
                        }
                    }
                } else {
                    if (position == SeletcItemPosition) {
                        holder.label.setProgressAndCancelAnimation(100, true);
                    } else {
                        holder.label.setProgressAndCancelAnimation(0, true);
                    }
                }
            }
        }
        return convertView;
    }

    /**
     * 在onitemClick中调用
     *
     * @param seletcItemPosition
     * @param view
     */
    public void setSeletcItemPosition(int seletcItemPosition, View view) {
        SeletcItemPosition = seletcItemPosition;
        RelativeLayout layout = (RelativeLayout) view;
        if (mType == MAIN_FILTER_TYPE) {
            final AnimationTextView tv = (AnimationTextView) layout.findViewById(R.id.filter_item_text);
            tv.setProgressAndCancelAnimation(100, false);
            /**
             * 将没有选中的恢复默认
             */
            ViewGroup vp = (ViewGroup) layout.getParent();
            int child = vp.getChildCount();
            for (int i = 0; i < child; i++) {
                View v = vp.getChildAt(i);
                AnimationTextView tv2 = (AnimationTextView) v.findViewById(R.id.filter_item_text);
                if (tv2 != tv) {
                    tv2.setProgressAndCancelAnimation(0, true);
                }
            }
            View iview = layout.findViewById(mImageViewId);
            if (iview == null) {
                restoreUnselectedView();
                layout.addView(mImageView);
            }
        } else {
            final AnimationTextView tv = (AnimationTextView) layout.findViewById(R.id.filter_item_text);
            tv.startInAnimation(250, true);
            /**
             * 将没有选中的恢复默认
             */
            ViewGroup vp = (ViewGroup) layout.getParent();
            int child = vp.getChildCount();
            for (int i = 0; i < child; i++) {
                View v = vp.getChildAt(i);
                AnimationTextView tv2 = (AnimationTextView) v.findViewById(R.id.filter_item_text);
                if (tv2 != tv) {
                    if (tv2.getProgress() != 0) {
                        tv2.startOutAnimation(250, true);
                    } else {
                        tv2.setProgressAndCancelAnimation(0, true);
                    }
                }
            }
        }
    }

    /**
     * @param seletcItemPosition
     */
    public void setSeletcItemPosition(int seletcItemPosition) {
        SeletcItemPosition = seletcItemPosition;
    }
//  可以用这种方式刷新ListView中的某个条目
//	public void updateView(int itemIndex) {
//		//得到第一个可显示控件的位置，
//		int visiblePosition = mListView.getFirstVisiblePosition();
//		//只有当要更新的view在可见的位置时才更新，不可见时，跳过不更新
//		if (itemIndex - visiblePosition >= 0) {
//			//得到要更新的item的view
//			View view = mListView.getChildAt(itemIndex - visiblePosition);
//			//从view中取得holder
//			ViewHolder holder = (ViewHolder) view.getTag();
//			HashMap<String, Object> item = data.get(itemIndex);
//
//			holder.listItem = (RelativeLayout) view.findViewById(R.id.rl_item);
//			holder.ibPlay = (ImageButton) view.findViewById(R.id.ib_play);
//			holder.ibDelete = (ImageButton) view.findViewById(R.id.ib_delete);
//			holder.tvName = (TextView) view.findViewById(R.id.tv_record_sound_name);
//			holder.tvLastModifyTime = (TextView) view
//					.findViewById(R.id.tv_record_time);
//			holder.tvCurrentPlayTime = (TextView) view
//					.findViewById(R.id.tv_current_play_time);
//			holder.tvTotalTime = (TextView) view.findViewById(R.id.tv_total_time);
//			holder.sb = (MySeekBar) view.findViewById(R.id.pb_play);
//			holder.layout = (LinearLayout) view
//					.findViewById(R.id.play_progress_info);
//
//			updateData(itemIndex, holder, item);
//		}
//	}

    /**
     * 恢复默认并刷新View会刷新View
     * 特殊处理用于编辑界面
     *
     * @param vp
     */
    public void resetSelectItemositionAndResetView(ViewGroup vp) {
        SeletcItemPosition = 0;
        if (mType == Edit_FILTER_TYPE || mType == VIDEO_FILTER_TYPE || mType == COLLAGE_FILTER_TYPE) {
            int child = vp.getChildCount();
            for (int i = 0; i < child; i++) {
                View v = vp.getChildAt(i);
                View image = v.findViewById(R.id.filter_item_image);
                Object o = image.getTag();
                if (o != null && o instanceof FilterBean) {
                    AnimationTextView tv = (AnimationTextView) v.findViewById(R.id.filter_item_text);
                    FilterBean data = (FilterBean) o;
                    int type = data.getType();
                    if (type == FilterConstant.TYPE_ORIGINAL) {
                        if (tv.getProgress() != 100) {
                            tv.startInAnimation(250, true);
                        }
                    } else {
                        if (tv.getProgress() != 0) {
                            tv.startOutAnimation(250, true);
                        } else {
                            tv.setProgressAndCancelAnimation(0, true);
                        }
                    }
                }
            }
        }
    }

    /**
     * 将没有被选中的恢复默认
     */
    private void restoreUnselectedView() {
        ViewParent viewP = mImageView.getParent();
        if (viewP != null) {
            RelativeLayout layout = (RelativeLayout) viewP;
            layout.removeView(mImageView);
        }
    }

    /**
     * 移除new标识 和 动画
     * 用于点击了More的处理
     *
     * @param view
     */
    public void setmShowNewFalse(View view) {
        this.mShowNew = false;
        // TODO: 17/4/17
    }

    /**
     * 移除new标识 和 动画
     * 用于和preference不一致时的处理
     */
    public void changeShowNewFalse() {
        this.mShowNew = false;
        notifyDataSetChanged();
    }

    /**
     * 获取showNew的标志
     */
    public boolean getShowNew() {
        return mShowNew;
    }

    /**
     * 启动More button的Animation
     */
    public void startAnimation() {
    }

    /**
     * 用于ArrayAdapter中getView的缓存
     */
    private class ViewHolder {
        AnimationTextView label;
        ImageView icon;
        ImageView vipIcon;
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public FilterBean getItem(int position) {
        if (position < mData.size()) {
            return mData.get(position);
        }
        return null;
    }

    @Override
    public boolean isEnabled(int position) {
        return super.isEnabled(position);
    }

    public void setData(List<FilterBean> data) {
        this.mData = data;
    }

    public int getSeletcItemPosition() {
        return SeletcItemPosition;
    }

    /**
     * @param bitmap
     */
    public void setBaseBitmap(Bitmap bitmap) {
        mIconManager.setBaseBitmap(bitmap);
        notifyDataSetChanged();
    }

    public void onDestory() {
        mIconManager.onDestory();
    }

    public int getFilterIndex(String filterPackageName) {
        int i = 0;
        for (FilterBean filterBo : mData) {
            if (TextUtils.equals(filterBo.getPackageName(), filterPackageName)) {
                return i;
            }
            i++;
        }
        return -1;
    }

    public String getFilterPackageName(int index) {
        if (index < mData.size()) {
            return mData.get(index).getPackageName();
        }
        return null;
    }
}
